package com.cloud.zk.service;

import com.cloud.utils.ZooKeeperUtil;
import org.apache.zookeeper.KeeperException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.List;

@Service
public class ZooKeeperService {

    @Value("${zookeeper.server}")
    private String connectString;
    @Value("${zookeeper.enable:false}")
    private Boolean enable;

    private ZooKeeperUtil zooKeeperUtil;

    @PostConstruct
    private void init() throws IOException {
        if (enable) {
            zooKeeperUtil = new ZooKeeperUtil(connectString);
        }

    }

    public void createNode(String path, String data) throws KeeperException, InterruptedException {
        zooKeeperUtil.createNode(path, data.getBytes());
    }

    public String getNodeData(String path) throws KeeperException, InterruptedException {
        byte[] data = zooKeeperUtil.getNodeData(path);
        return new String(data);
    }

    public List<String> getChildren(String path) throws KeeperException, InterruptedException {
        return zooKeeperUtil.getChildren(path);
    }
}